<template>
  <div class="app-container">
    <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/getEmployeesSimple'
export default {
  name: 'Import',
  data() {
    return {
      tableData: [],
      tableHeader: []

    }
  },
  methods: {
    async doAdd(data) {
      try {
        const res = await importEmployee(data)
        this.$message.success(res.message)
        // 回退
        this.$router.back()
      } catch (error) {
        this.$message.error(error)
      }
    },
    transExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const results = data.map(zhObj => {
        // console.log(zhObj, 'zhObj');
        const zhKeys = Object.keys(zhObj)
        console.log(zhKeys, 'zhKeys')
        const enObj = {}
        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // 后端需要的日期格式是标准时间
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
      return results
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      console.log(results, 'results')
      console.log(header, 'header')
      // 1.读取excel表格转化为行和列的数据
      // 2.按数据接口文档要求进行格式转化 将中文转化为英文
      const data = this.transExcel(results)
      console.log(data, 'data-------------------------------------')
      // 3.发送请求,实现数据的批量导入
      this.doAdd(data)
    }
  }
}
</script>
